package org.example.mybatisplus.config;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class RequestLoggingInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(RequestLoggingInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求信息
        String method = request.getMethod();
        String url = request.getRequestURI();
        String remoteAddr = request.getRemoteAddr();
        String queryString = request.getQueryString();

        // 输出日志
        logger.info("Request received: {} {} from {}", method, url, remoteAddr);
        if (queryString != null) {
            logger.info("Query String: {}", queryString);
        }

        // 可以在这里添加更多逻辑，例如记录请求头、请求体等
        request.getHeaderNames().asIterator().forEachRemaining(headerName ->
                logger.info("Header {}: {}", headerName, request.getHeader(headerName)));

        return true;
    }
}